/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package parsers;

import common.Application;
import common.Initializer;
import dao.Property;
import database.DatabaseObject;
import database.DatabaseObjectFactory;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.LinkedList;
import runtime.RuntimeInstanceFactory;
import templates.PropertyTemplate;
import templates.Template;

public class SqlParser implements Initializer {

    private ResultSet rs;

    public SqlParser(ResultSet rs) {
        this.rs = rs;
    }

    @Override
    public Object init(Object obj) {
        short uid = (Short) obj;
        Collection<Property> properties = new LinkedList<Property>();
        Application app = Application.getInstance();
        Template template = app.getTemplate(uid);
        Iterable<PropertyTemplate> propertyTemplates = template.getPropertyTemplateCollection();
        RuntimeInstanceFactory factory = new DatabaseObjectFactory();
        for (PropertyTemplate pt : propertyTemplates) {
            try {
                DatabaseObject value = (DatabaseObject) factory.getObject(pt.getType());
                if (rs.getString(pt.getName()) != null) {
                    value.setValue(rs.getString(pt.getName()));
                } else {
                    if (pt.isNullEnabled()) {
                        value.setValue(pt.getNullValue());
                    }
                }
                properties.add(new Property(pt.getUid(), value));
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
        }
        return properties;
    }

    @Override
    public void setManagedObject(Initializer.ObjectType obj) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
